﻿using System.Collections;
using System.Collections.Generic;
using System.ComponentModel;
using System;
using UnityEngine;

public class EnemyBase : MonoBehaviour
{
    /// <summary>
    /// 移动委托
    /// </summary>
    protected delegate void moveDelegate();
    /// <summary>
    /// 死亡委托
    /// </summary>
    protected delegate void deathDelegate();

    /// <summary>
    /// 移动时事件
    /// </summary>
    protected event moveDelegate OnMove;
    /// <summary>
    /// 死亡时事件
    /// </summary>
    protected event deathDelegate OnDeath;


    public Animator animator;

    /// <summary>
    /// 移动速度
    /// </summary>
    public float speed = 3;

    /// <summary>
    /// 伤害
    /// </summary>
    public int power = 1;

    /// <summary>
    /// 加速后的速度
    /// </summary>
    public float speed2 = 5;
    /// <summary>
    /// 类型
    /// </summary>
    public EnemyType type = EnemyType.normal;
    /// <summary>
    /// 颜色
    /// </summary>
    public MyColors.MyColor color = MyColors.RED;

    public Rigidbody2D rigid;

    public Transform checkOrigin; //检测原点

    protected Vector3 forwardDownCheckPoint; //前下方检测点
    protected Vector3 downCheckPoint; //下方检测点
    protected Vector3 forwardCheckPoint; //前方

    [Range(-1, 1)]
    public int moveForward = -1; //移动方向(1右 -1左）

    protected bool isFoundPlayer = false;

    /// <summary>
    /// 初始化
    /// </summary>
    public void InitEnemy()
    {
        if (rigid == null)
        {
            rigid = this.gameObject.AddComponent<Rigidbody2D>();
        }

    }

    protected void FixedUpdate()
    {
        Move();

        var hitUp = Physics2D.RaycastAll(checkOrigin.position, (forwardCheckPoint - checkOrigin.position).normalized * -1, 5f, LayerMask.GetMask("Player"));
    }

    /// <summary>
    /// 移动
    /// </summary>
    public void Move()
    {
        //  animator.SetBool("move", true);       
        var f = moveForward >= 0 ? 1 : -1;
        forwardCheckPoint = new Vector3(0.5f * f, 0, 0) + checkOrigin.position;
        forwardDownCheckPoint = new Vector3((0.5f) * f, (-0.5f), 0) + checkOrigin.position;
        downCheckPoint = (checkOrigin.up * -1) * 0.5f + checkOrigin.position;
        transform.localScale = new Vector3(f, 1, 1);

        if (CheckRoad() && !CheckWall())
        {
            rigid.velocity = new Vector2(moveForward * speed, rigid.velocity.y);
        }
        else
        {
            rigid.velocity = new Vector2(0, rigid.velocity.y);
            moveForward *= -1;
        }

        if (OnMove != null)
        {
            OnMove();
        }

        if (!isFoundPlayer)
        {
            if (IsWithPlayer())
            {
                isFoundPlayer = true;
                speed = speed2;
            }
        }

    }

    /// <summary>
    /// 是否和玩家在一起
    /// </summary>
    /// <returns></returns>
    private bool IsWithPlayer()
    {
        var hitF = Physics2D.RaycastAll(checkOrigin.position, (forwardCheckPoint - checkOrigin.position).normalized, 10f, LayerMask.GetMask("Player"));
        var hitB = Physics2D.RaycastAll(checkOrigin.position, (forwardCheckPoint - checkOrigin.position).normalized * -1, 10f, LayerMask.GetMask("Player"));
        Debug.DrawRay(checkOrigin.position, (forwardCheckPoint - checkOrigin.position) * -1 * 10, Color.red);
        Debug.DrawRay(checkOrigin.position, (forwardCheckPoint - checkOrigin.position) * 10, Color.red);

        if (hitF.Length > 0 || hitB.Length > 0)
        {
            return true;
        }
        else
        {
            return false;
        }
    }

    /// <summary>
    /// 检测是否碰到墙
    /// </summary>
    /// <returns>是/否</returns>
    private bool CheckWall()
    {
        Debug.DrawRay(checkOrigin.position, forwardCheckPoint - checkOrigin.position, Color.yellow);
        RaycastHit2D hit;
        hit = Physics2D.Raycast(checkOrigin.position, (forwardCheckPoint - checkOrigin.position).normalized, 0.5f, LayerMask.GetMask("Ground"));
        if (hit.collider != null)
        {
            return true;
        }
        else
        {
            return false;
        }
    }

    /// <summary>
    /// 检查是否有路
    /// </summary>
    /// <returns>是/否</returns>
    private bool CheckRoad()
    {
        Debug.DrawRay(checkOrigin.position, forwardDownCheckPoint - checkOrigin.position, Color.red);
        // Debug.DrawLine(checkOrigin.position, forwardDownCheckPoint, Color.green);
        RaycastHit2D hit;
        hit = Physics2D.Raycast(checkOrigin.position, (forwardDownCheckPoint - checkOrigin.position).normalized, 0.5f, LayerMask.GetMask("Ground"));
        if (hit.collider != null)
        {
            // Debug.Log(hit.collider.name);
            return true;
        }
        else
        {
            return false;
        }
    }

    /// <summary>
    /// 死亡
    /// </summary>
    public void Die()
    {
        //animator.SetBool("death", true);
        Debug.Log(2);
        this.gameObject.SetActive(false);
        OnDeath();
        //StartCoroutine(WaitAnimationEnd("death"));
    }



    protected IEnumerator WaitAnimationEnd(string name)
    {
        while (true)
        {
            yield return new WaitForEndOfFrame();
            var stateInfo = animator.GetCurrentAnimatorStateInfo(0);
            if (stateInfo.IsName(name) && stateInfo.normalizedTime >= 0.95f)
            {
                this.gameObject.SetActive(false);
                if (OnDeath != null)
                {
                    OnDeath();
                }
                yield break;
            }
        }
    }

    private void OnDrawGizmos()
    {
        Gizmos.DrawSphere(forwardDownCheckPoint, 0.02f);
    }

    //伤害主角用
    public void OnCollisionEnter2D(Collision2D collision)
    {
        if (collision.collider.tag == "Player")
        {
            //Debug.Log("扣血探测");
            PlayerHealth player = collision.collider.GetComponent<PlayerHealth>();
            if (player != null)
            {
                Debug.Log("扣血");
                player.ReduceBlood(power);
            }
        }
    }

    /// <summary>
    /// 史莱姆类型
    /// </summary>
    public enum EnemyType
    {
        /// <summary>
        /// 正常史莱姆
        /// </summary>
        normal,
        /// <summary>
        /// 尖刺史莱姆
        /// </summary>
        spike
    }
}
